package com.sdruixinggroup.mondayb2b.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.Member;
import com.sdruixinggroup.mondayb2b.models.ModelBeen;
import com.sdruixinggroup.mondayb2b.models.UploaderResponse;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.sdruixinggroup.mondayb2b.widget.GlideCircleTransform;
import com.squareup.picasso.Picasso;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import me.nereo.multi_image_selector.MultiImageSelectorFragment;
import okhttp3.Call;

/**
 * Created by tangjie on 2017/11/11.
 */

public class MineDetailActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.iv_headers)
    ImageView ivHeaders;
    @BindView(R.id.tv_nick)
    TextView tvNick;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    private ImageView topbar_left;
    private TextView topbar_center;
    private RelativeLayout my_photo, my_name, my_sex, my_username, my_phone;
    private Intent intent = new Intent();
    //image upload
    public static final int IMAGE_REQUEST_CODE = 0x103;
    public final static int compressBySizeWidth = 720;
    public final static int compressBySizeHeight = 1280;
    private  int gender = -1;
    private String nickname;
    private String imangeURl = "";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_detail);
        ButterKnife.bind(this);

        initView();
    }

    private void initView() {
        topbar_left = (ImageView) findViewById(R.id.topbar_left);
        topbar_center = (TextView) findViewById(R.id.topbar_title);

        topbar_center.setText("个人信息");

        my_photo = (RelativeLayout) findViewById(R.id.my_photo);
        my_name = (RelativeLayout) findViewById(R.id.my_name);
        my_sex = (RelativeLayout) findViewById(R.id.my_sex);
        my_username = (RelativeLayout) findViewById(R.id.my_username);
        my_phone = (RelativeLayout) findViewById(R.id.my_phone);


        registerLinstener();
    }

    private void registerLinstener() {
        topbar_left.setOnClickListener(this);
        my_name.setOnClickListener(this);
        my_photo.setOnClickListener(this);
        my_username.setOnClickListener(this);
        my_phone.setOnClickListener(this);
        my_sex.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        if (view == topbar_left) {
            finish();
        }
        if (view == my_photo) {
            initgetPhotoview();
            return;
        }else if (view == my_name) {
            intent.putExtra("code", 0);
            intent.setClass(this, CommitNameActivity.class);
            intent.putExtra("nickname",nickname);
            startActivity(intent);
            return;
        }else if (view == my_sex) {
            intent.setClass(this, SexActivity.class);
            intent.putExtra("gender",gender);
            startActivityForResult(intent,3);
            return;
        }
    }

    /**
     * popupwindow
     */
    private void initgetPhotoview() {
        Intent intent = new Intent(MineDetailActivity.this, MultiImageSelectorActivity.class);
        // whether show camera
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // max select image amount
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
        // select mode (MultiImageSelectorActivity.MODE_SINGLE OR MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        startActivityForResult(intent, IMAGE_REQUEST_CODE);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case IMAGE_REQUEST_CODE:

                ArrayList<String> selectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if (selectPath != null && selectPath.size() > 0) {
                    for (int i = 0; i < selectPath.size(); ++i) {
                        imangeURl =selectPath.get(i);
                        final   String urlPic = compressUploadPicture(selectPath.get(i));
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                  Glide.with(getApplicationContext()).load(urlPic).transform(new GlideCircleTransform(getApplicationContext())).into(ivHeaders);
                            }
                        });


                        //updatePic(urlPic);
                        uploadPic(urlPic);
                    }
                }
                break;
            case 3:

                break;
        }
    }

    private String compressUploadPicture(String imagePath) {

        String compressPath = Environment.getExternalStorageDirectory()
                + File.separator + SystemClock.currentThreadTimeMillis() + ".jpg";
        File file = new File(imagePath);
        if (file.exists()) {
            Bitmap bitmap = compressBySize(imagePath, compressBySizeWidth,
                    compressBySizeHeight);
            // 保存图片
            try {
                saveFile(bitmap, compressPath);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return compressPath;
        } else {
            return null;
        }
    }

    // 存储进SD卡
    public void saveFile(Bitmap bm, String fileName) throws Exception {
        File dirFile = new File(fileName);
        // 检测图片是否存在
        if (dirFile.exists()) {
            dirFile.delete(); // 删除原图片
        }
        File myCaptureFile = new File(fileName);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(myCaptureFile));
        // 100表示不进行压缩，70表示压缩率为30%
        bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
    }

    // 压缩图片尺寸
    public Bitmap compressBySize(String pathName, int targetWidth,
                                 int targetHeight) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;// 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
        Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);
        // 得到图片的宽度、高度；
        float imgWidth = opts.outWidth;
        float imgHeight = opts.outHeight;
        // 分别计算图片宽度、高度与目标宽度、高度的比例；取大于等于该比例的最小整数；
        int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
        int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
        opts.inSampleSize = 1;
        if (widthRatio > 1 || widthRatio > 1) {
            if (widthRatio > heightRatio) {
                opts.inSampleSize = widthRatio;
            } else {
                opts.inSampleSize = heightRatio;
            }
        }
        // 设置好缩放比例后，加载图片进内容；
        opts.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(pathName, opts);

        bitmap = rotateBitmapByDegree(bitmap, getImageDegree(pathName));
        return bitmap;
    }


    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm     需要旋转的图片
     * @param degree 旋转角度
     * @return 旋转后的图片
     */
    public Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }


    private int getImageDegree(String path) {
        int degree = 0;
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    private void queryData() {
        String url = API.MEMBER + "access_token=" + UserInfoUtil.getInfoToken(getApplicationContext());
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");
        TypeToken<Member> typeToken = new TypeToken<Member>() {
        };
        OkHttpUtils.get().url(url).headers(heades).build().execute(new ObjectCallBack<Member>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(Member response, int id) {
                if (null != response) {
                    if (response.getErr_code() == 0) {
                        Member.MemberBean bean = response.getMember();
                        tvNick.setText(bean.getNickname());
                        nickname = bean.getNickname();
                       gender= bean.getGender();
                        if(gender == 1){
                            tvSex.setText("男");
                        }else  if(gender == 2) {
                            tvSex.setText("女");
                        }else {
                            tvSex.setText("--");
                        }
                      String username= bean.getUsername();
                        if(!TextUtils.isEmpty(username)){
                            tvName.setText(username);
                        }
                        tvPhone.setText(bean.getMobile());
                        if(!TextUtils.isEmpty(imangeURl)){
                            Glide.with(getApplicationContext()).load(imangeURl).transform(new GlideCircleTransform(getApplicationContext()))
                                    .error(R.drawable.personal_portrait).into(ivHeaders);
                        }else {
                            Glide.with(getApplicationContext()).load(bean.getAvatar()).transform(new GlideCircleTransform(getApplicationContext()))
                                    .error(R.drawable.personal_portrait).into(ivHeaders);
                        }


                    } else {
                        showToast(response.getErr_msg());
                    }
                }
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
            queryData();
    }

    private void updateHeaderPic(final String imgeurl){
        String url = API.MEMBER_AVATAR+imgeurl+"&access_token="+ UserInfoUtil.getInfoToken(this);
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");
        TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>() {
        };

        OkHttpUtils.get().url(url).headers(heades).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ModelBeen response, int id) {
                        if(response.err_code == 0){
                            showToast("头像修改成功");
                            EventBus.getDefault().post(123);
                        }
            }
        });



    }


    private void uploadPic(String picurl){
        String url = API.UPLOAD +UserInfoUtil.getInfoToken(getApplicationContext());
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");
        TypeToken<UploaderResponse> typeToken = new TypeToken<UploaderResponse>() {
        };
        File file = new File(picurl);
        OkHttpUtils.post()//
                .addFile("mFile", file.getName(), file)
                .url(url)
                .headers(heades)//
                .build()//
                .execute(new ObjectCallBack<UploaderResponse>(typeToken) {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(UploaderResponse response, int id) {
                                if(response.getErr_code() == 0){
                                String urlpic =  response.getResult().getMFile();
                                    updateHeaderPic(urlpic);
                                }else {
                                    showToast(response.getErr_msg());
                                }
                    }
                });
    }
}
